#include <unistd.h>
#include <string.h>
#include <curl/curl.h>

int upload_file(const char *path)
{
	CURLcode res;
	CURL *curl = curl_easy_init();
	curl_mime *multipart = curl_mime_init(curl);
	curl_mimepart *part = curl_mime_addpart(multipart);
	curl_mime_name(part, "upgrade_image");
	curl_mime_filedata(part, path);
	curl_easy_setopt(curl, CURLOPT_MIMEPOST, multipart);
	curl_easy_setopt(curl, CURLOPT_URL, "http://[fe80::baba:68ff:feac:dead%eth0.13]/boaform/web_form_upload_file.cgi");
	res = curl_easy_perform(curl);
	curl_mime_free(multipart);
	curl_easy_cleanup(curl);
	return res;
}
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp)
{
	char *buf = (char *)userp;
	memcpy(buf, buffer, size * nmemb);
	buf[size * nmemb] = 0;
	return size * nmemb;
}

int check_status()
{
	CURLcode res;
	char buf[1024];
	const char *data = "name=get_upgrade_status";

	CURL *curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, buf);
	curl_easy_setopt(curl, CURLOPT_URL, "http://[fe80::baba:68ff:feac:dead%eth0.13]/boaform/get_upgrade_status.cgi");
	int flag = 1;
	while (flag) {
		printf("curl_easy_perform\n");
		res = curl_easy_perform(curl);
		if (res != CURLE_OK) {
			fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
		} else {
			printf("%s\n", buf);
		}
		sleep(1);
	}
	return 0;
}

int main()
{
	CURLcode res;
	curl_global_init(CURL_GLOBAL_ALL);
	if ((res = upload_file("/tftpboot/V1.2.7_release.bin")) != CURLE_OK) {
		fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
	}
	check_status();
	curl_global_cleanup();
	return 0;
}
